/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Facades;

import Entities.Message;
import Entities.User;
import Entities.UserMessages;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author roycalderon
 */
@Stateless
public class UserMessagesFacade extends AbstractFacade<UserMessages> {

    @PersistenceContext(unitName = "MaRoY-LibraryPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public UserMessagesFacade() {
        super(UserMessages.class);
    }

    /*    
     * Obtiene los mensajes No leidos
     * @author royCalderon
     */
    public List<UserMessages> getUnreadUserMessages(int userId) {
        Query q = em.createNamedQuery("UserMessages.findByUserid");
        q.setParameter("userId", userId);
        q.setParameter("status", "U");
        try {
            List<UserMessages> ListAux = (List<UserMessages>) q.getResultList();
            if (ListAux != null) {
                return ListAux;
            }
            else
                return null;
        } catch (Exception e) {
        }
        return null;
    }
    
    /*    
     * Obtiene los ID de usuario de los cuales tengo unread messages
     * @author royCalderon
     */
    public int[] getUnreadUserMessagesUsersID(int userId) {
        Query q = em.createNamedQuery("UserMessages.findByUserid");
        q.setParameter("userId", userId);
        q.setParameter("status", "U");
        
        
        try {
            List<UserMessages> ListAux = (List<UserMessages>) q.getResultList();
            int listaUsr[]=new int[ListAux.size()];
            int i=0;
            for (UserMessages userMessagesIterator : ListAux) {
                
                 listaUsr[i++]=userMessagesIterator.getUserid().getId();
            }
            if (ListAux != null) {
                return listaUsr;
            }
            else
                return null;
        } catch (Exception e) {
        }
        return null;
    }

    /*    
     * Obtiene los mensajes del usuario
     * @author royCalderon
     */
    public List<Message> getMessageUser(Integer iduser, Integer idusermessage) {
        Query q = em.createQuery("SELECT um.message FROM UserMessages um "
                + "WHERE (um.UserMessagesPK.userId = :idusermessage "
                + "AND um.message.userid.id= :iduser) or (um.UserMessagesPK.userId = :iduser "
                + "AND um.message.userid.id = :idusermessage) "
                + "ORDER BY um.message.date ASC");
        q.setParameter("idusermessage", iduser);
        q.setParameter("iduser", idusermessage);
        try {
            return (List<Message>) q.getResultList();
        } catch (Exception e) {
            return null;
        }
    }
}
